import cv2
import numpy as np
import random

class RectangleDetector:
    def __init__(self):
        """初始化矩形检测器"""
        pass
    
    def detect_rectangles(self, image):
        """检测图片中的矩形并返回随机选中矩形上的一个点坐标"""
        if image is None:
            print("输入图像为空")
            return None
        
        # 转换为灰度图
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
        # 高斯模糊
        blurred = cv2.GaussianBlur(gray, (5, 5), 0)
        
        # 边缘检测
        edges = cv2.Canny(blurred, 50, 150)
        
        # 查找轮廓
        contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        all_points = []
        selected_point = None
        
        # 处理每个轮廓
        for contour in contours:
            # 计算轮廓的近似多边形
            peri = cv2.arcLength(contour, True)
            approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
            
            # 如果是四边形（矩形）
            if len(approx) == 4:
                # 计算最小外接矩形
                rect = cv2.minAreaRect(contour)
                box = cv2.boxPoints(rect)
                box = np.int0(box)
                
                # 存储所有顶点
                for point in box:
                    all_points.append(tuple(point))
        
        # 如果有检测到矩形，随机选择一个顶点作为选中点
        if all_points:
            selected_point = random.choice(all_points)
            print(f"随机选中矩形上的点坐标: {selected_point}")
        
        return selected_point

if __name__ == "__main__":
    # 示例用法
    detector = RectangleDetector()
    
    # 从文件读取图像
    image_path = "test.jpg"  # 替换为你的图片路径
    image = cv2.imread(image_path)
    
    if image is not None:
        point = detector.detect_rectangles(image)
        if point:
            print(f"最终返回的点坐标: {point}")
        else:
            print("未检测到矩形")
    else:
        print("无法读取图片")